package ch.sv7.tool.dbmanager.db.fixbuilder;

import java.util.List;

import ch.sv7.tool.dbmanager.Context;
import ch.sv7.tool.dbmanager.db.IndexSchema;
import ch.sv7.tool.dbmanager.db.dialect.Dialect;
import ch.sv7.tool.dbmanager.db.difference.IndexNameDifference;
import ch.sv7.tool.dbmanager.db.difference.SchemaDifference;
import ch.sv7.tool.dbmanager.db.fix.CreateIndexFix;
import ch.sv7.tool.dbmanager.db.fix.DropIndexFix;
import ch.sv7.tool.dbmanager.db.fix.RenameIndexFix;
import ch.sv7.tool.dbmanager.db.fix.SchemaFix;

/**
 * TODO: Document me!
 *
 * @author svt
 *
 */
public class IndexNameFixBuilder implements FixBuilder {

	public SchemaFix[] createFixes(SchemaDifference difference, Dialect dialect, Context context) {
		IndexNameDifference indexNameDifference = (IndexNameDifference)difference;
		/*
		 * Check if expected index name already exists
		 */
		String expectedName = indexNameDifference.getExpectedIndex().getName();
		List indexes = indexNameDifference.getActualIndex().getTableSchema().getIndexes();
		boolean indexNameExists = false;
		for (int i=0; i<indexes.size(); i++) {
			IndexSchema index = (IndexSchema)indexes.get(i);
			if (index.getName().equals(expectedName)){
				indexNameExists = true;
				break;
			}
		}
		if (indexNameExists) {
			SchemaFix dropFix = new DropIndexFix(indexNameDifference.getActualIndex());
			SchemaFix createFix = new CreateIndexFix(indexNameDifference.getExpectedIndex());		
			return new SchemaFix[]{ dropFix, createFix };		
		} else {
			SchemaFix fix = new RenameIndexFix(indexNameDifference.getActualIndex(), indexNameDifference.getExpectedIndex());
			return new SchemaFix[]{ fix };
		}
	}

}
